package com.example.simple;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 简单的缓存实现
 * 演示AOP的概念
 */
public class SimpleCache {

    private static final ConcurrentHashMap<String, CacheEntry> cache = new ConcurrentHashMap<>();

    /**
     * 缓存条目
     */
    private static class CacheEntry {
        private final Object value;
        private final long expireTime;

        public CacheEntry(Object value, long expireTime) {
            this.value = value;
            this.expireTime = expireTime;
        }

        public Object getValue() {
            return value;
        }

        public boolean isExpired() {
            return System.currentTimeMillis() > expireTime;
        }
    }

    /**
     * 获取缓存值
     */
    public static Object get(String key) {
        CacheEntry entry = cache.get(key);
        if (entry != null && !entry.isExpired()) {
            System.out.println("缓存命中: " + key);
            return entry.getValue();
        }
        return null;
    }

    /**
     * 设置缓存值
     */
    public static void put(String key, Object value, int expireSeconds) {
        long expireTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(expireSeconds);
        cache.put(key, new CacheEntry(value, expireTime));
        System.out.println("缓存设置: " + key + " -> " + value);
    }

    /**
     * 清除缓存
     */
    public static void clear() {
        cache.clear();
    }

    /**
     * 生成缓存键
     */
    public static String generateKey(String className, String methodName, Object... args) {
        StringBuilder keyBuilder = new StringBuilder();
        keyBuilder.append(className).append(".").append(methodName);

        if (args.length > 0) {
            keyBuilder.append("(");
            for (int i = 0; i < args.length; i++) {
                if (i > 0)
                    keyBuilder.append(",");
                keyBuilder.append(args[i]);
            }
            keyBuilder.append(")");
        }

        return keyBuilder.toString();
    }
}
